<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Selibra\Config;


use Selibra\Files\Config;
use Symfony\Component\Yaml\Yaml as SYaml;

class Yaml
{

    /**
     * @var $this
     */
    private static $ins;


    /**
     * @var array
     */
    protected static $confis = [];


    /**
     * Yaml constructor.
     */
    private function __construct()
    {
        // TODO 读取配置文件
        foreach ($GLOBALS['argv'] as $key => $argvItem) {
            if (str_starts_with($argvItem, '--config-dir=')) {
                $configDir = str_replace('--config-dir=', '', $argvItem);
                break;
            }
        }
        $configDir = $configDir ?? 'Resource';
        $rootPath = \Selibra\Files\Config::getRootPath();
        $configPath = $rootPath . DIRECTORY_SEPARATOR . $configDir . DIRECTORY_SEPARATOR;
        // 遍历文件
        $files = scandir($configPath);
        $configFiles = [];
        foreach ($files as $file) {
            if (substr($file, -4) === '.yml') {
                array_push($configFiles, $file);
                // 读取
                $configs = SYaml::parse(file_get_contents($configPath . $file));
                self::$confis = array_merge(self::$confis, $configs);
            }
        }
    }


    /**
     * 获取配置
     * @param $key
     * @return mixed
     */
    public function get($key, $g = null)
    {
        $keyArray = explode('.', $key);
        if (empty($g)) {
            $g = self::$confis;
        }
        $gKey = array_shift($keyArray);
        if (!array_key_exists($gKey, $g)) {
            return null;
        }
        $config = $g[$gKey];
        if (!empty($keyArray)) {
            return $this->get(implode('.', $keyArray), $config);
        } else {
            return $config;
        }
    }


    /**
     * 获取配置
     * @param $key
     * @return mixed
     */
    public function has($key, $g = null)
    {
        $keyArray = explode('.', $key);
        if (empty($g)) {
            $g = self::$confis;
        }
        $gKey = array_shift($keyArray);
        if (!array_key_exists($gKey, $g)) {
            return false;
        }
        $config = $g[$gKey];
        if (!empty($keyArray)) {
            return $this->get(implode('.', $keyArray), $config);
        } else {
            return true;
        }
    }


    /**
     * 获取单例
     * @return mixed
     */
    public static function getIns()
    {
        if (!isset(self::$ins)) {
            self::$ins = new Yaml();
        }
        return self::$ins;
    }

}
